python中strip()、lstrip()、rstrip()用法详解

您所在的位置:网站首页 python rstrip函数 python中strip()、lstrip()、rstrip()用法详解

python中strip()、lstrip()、rstrip()用法详解

2023-10-11 19:44| 来源: 网络整理| 查看: 265

Python中有三个去除头尾字符、空白符的函数,它们依次为:

strip: 用来去除头尾字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格);

lstrip:用来去除开头字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格);

rstrip:用来去除结尾字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格)。

从字面可以看出r=right,l=left,strip、rstrip、lstrip是开发中常用的字符串格式化的方法。

注意:这些函数都只会删除头和尾的字符,中间的不会删除。

函数语法分别为:

string.strip(str chars)

string.lstrip(str chars)

string.rstrip(str chars)

说明:“str chars”表示字符串

1、当chars为空时,默认删除空白符,也包括'\n'、'\r'、'\t'

str = ' hello world !' print(str.strip()) print(str.lstrip()) print(str.rstrip()) #打印结果如下: hello world ! hello world ! hello world !

2、当chars不为空时,则会删除字符串中头或者尾的chars字符内容

str = '# hello # world !#' print(str.strip('#')) print(str.lstrip('#')) print(str.rstrip('#')) #打印结果如下: hello # world ! hello # world !# # hello # world !

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3